<template>
	<view class="p30">
		<u-loading-icon :show="loadingStatus" text="正在加载..." textSize="14" size="17"></u-loading-icon>
		<view v-show="loadingStatus==false">
			<u-checkbox-group v-model="selection" activeColor="#06B7F3" placement="column" v-if="list.length">
				<view class="light-box-shadow item-box" :key="item.id" v-for="item in list">
					<view class="item-title">
						<view class="flex-between">
							<text>{{item.nickName}}</text>
							<u-checkbox v-if="selectMode" :name="item.id" shape="circle" label="选中"></u-checkbox>
							<view class="flex-row" v-else @click="editBikeFun(item)">
								<u-icon name="bianji" color="#AAB1C2" size="13" :isShowIcon="false"
									customPrefix="iconfontbike iconbike"></u-icon>
								<text style="color:#AAB1C2 ;" class="ml4">编辑</text>
							</view>
						</view>
					</view>
					<view class="content">
						<view class="flex-between" @click="selectBikeFun(item)">
							<view class="flex-row">
								<view style="position: relative;top:1px">
									<u-icon name="checkmark-circle-fill" color="#06B7F3" size="16" v-if="item.isSelect">
									</u-icon>
									<u-icon v-else name="xingzhuang-tuoyuanxing" color="#AAB1C2" size="16"
										:isShowIcon="false" customPrefix="iconfontbike iconbike"></u-icon>
								</view>
								<view class="ml10">
									<text>设备默认</text>
									<view class="mt10">
										<text class="c-desc">车辆名称：</text>
										<text>{{item.nickName}}</text>
									</view>
									<view class="mt10">
										<text class="c-desc">车架号码：</text>
										<text>{{item.vin}}</text>
									</view>
									<view class="mt10">
										<text class="c-desc">车牌号码：</text>
										<text>{{item.licensePlateNumber}}</text>
									</view>
									
								</view>
							</view>

							<view style="padding-right: 30px;">
								<image
									:src="deviceData.carPhotoLink ? deviceData.carPhotoLink  : '/static/images/index/bike.png'"
									style="width:80px;height:80px"></image>
							</view>
						</view>
						<view class="mt10 rz flex-between"  style="margin-left: 42upx;padding-right: 30px;">
							<view>
								<text class="c-desc">车辆认证：</text>
								<view class="inlineBlock" @click.stop="gotoAuthFun(item)">
									<text
										:class="['ml10',item.isAuth == '1' ? 'tag-warn' : 'tag-primary']">{{item.isAuth == "1" ? "去认证" : "已认证"}}</text>
									<u-icon size="25rpx" color="#06B7F3" name="arrow-rightward"
										v-if="item.isAuth == '1'"></u-icon>
								</view>
							</view>
							<text
								class="tag-primary border-none" @click="delCar(item)">解绑</text>
						</view>
					</view>
				</view>
			</u-checkbox-group>
			<cust-empty desc="暂无数据" v-else>
			</cust-empty>
			<view class="flex-center" v-if="!selectMode">
				<view style="width: 150px;" class="mt100">
					<u-button type="primary" text="新增车辆" :throttleTime="1000" @click="toAdd"></u-button>
				</view>
			</view>
		</view>

		<view v-if="selectMode" class="h140"></view>
		<fix-bottom-del v-if="selectMode" @cancel="handleCancel" @del="showDelConfirmDia"></fix-bottom-del>
		<u-modal :show="delConfirmDia" :title="delConfirmDiaTitle" :content="delConfirmDiaContent"
			:confirmText="delConfirmDiaYesBtn" :showCancelButton="true" :cancelText="delConfirmDiaNoBtn"
			@confirm="handleDel" @cancel="hideDelConfirmDia"></u-modal>

		<u-modal :show="show" title="编辑车辆名称" :showCancelButton="true" @cancel="cancel" @confirm="confirm">
			<u--input placeholder="请输入车辆名称" v-model="name">

			</u--input>
		</u-modal>
	</view>
</template>

<script>
	import Feedback from "../components/feedback";
	import delConfirm from "@/mixins/delConfirm";
	import FixBottomDel from "../components/fix-bottom-del";
	import custEmpty from "@/components/cust-empty/index.vue";
	import {
		dataPointMqttTopic,
		fenceMqttTopic,
		authTopic
	} from '@/api/http/setting';
	import {
		getCarListAPI,
		editCarAPI,
		removeCarAPI,
		verifyCarAPI
	} from "@/api/api/car.js"
	import {
		bluetoothStart,
		closeBLEConnection
	} from "@/static/bluetooth/core.js"

	import {
		getStoreSyncUtil
	} from "@/utils/store.js"
	import {
		$getCarDetail,
		mqttMSG,
		$currentRoute,
		client,
		throttle,
		getDifferenceDay
	} from "@/utils/utils.js"
	import {
		mapState
	} from 'vuex'
	export default {
		components: {
			Feedback,
			FixBottomDel,
			custEmpty
		},
		mixins: [delConfirm],
		data() {
			return {
				loadingStatus: true,
				show: false,
				name: '',
				list: [],
				selection: [],
				selectMode: false,
				delt: [],
				id: '',
				bike: {},
			}
		},
		onShow() {
			console.log("client", client);
			this.$store.commit("setSpecialAppOnShow", false);
			this.bike = this.currentBike;
			this.getCarListFun();
		},
		computed: {
			...mapState(["isToIndex", "deviceData", "isConnected", "currentBike"])
		},
		onLoad() {
			this.delConfirmDiaContent = '确定要解绑该车辆吗?';
			this.delConfirmDiaYesBtn= '确定解绑';
			this.delConfirmDiaNoBtn= '取消解绑';
		},
		onUnload(params) {
			//只针对车列表页面，不针对车辆绑定成功后销毁的页面
			if (!this.$validatenull(this.deviceData)) {
				if (!this.isToIndex) {
					let currentRoute = $currentRoute();
					if (currentRoute == "pages/views/home/userConfig" || currentRoute == "pagesMy/views/myMotorbike") {
						//如果切换了当前车辆,则重新连接mqtt并且尝试断开蓝牙并重新打开设备器搜索蓝牙
						if (!this.$validatenull(this.bike)) {
							if (this.currentBike.id != this.bike.id) {
								$getCarDetail(this.bike.id, () => {
									let oldEcuid = this.currentBike.ecuId;
									let topicalDataPoint = dataPointMqttTopic + this.currentBike.ecuId; //上报数据推送
									let isCrossFence = fenceMqttTopic + this.currentBike.ecuId; //电子围栏是否超出区域推送
									let isAuthTopic = authTopic + this.currentBike.ecuId; //电子围栏是否超出区域推送
									if (!this.$validatenull(client) && client
										.connected) { // 如果当前处于连接状态，则不在重新连接，则直接取消订阅和重新订阅
										client.unsubscribe([topicalDataPoint, isCrossFence, isAuthTopic],
											async error => {
												if (!error) {
													console.log("取消订阅成功" + oldEcuid);
												} else {
													console.log("取消订阅失败" + oldEcuid);
												}
											});
										topicalDataPoint = dataPointMqttTopic + this.bike.ecuId; //上报数据推送
										isCrossFence = fenceMqttTopic + this.bike.ecuId; //电子围栏是否超出区域推送
										isAuthTopic = authTopic + this.bike.ecuId; //电子围栏是否超出区域推送
										let newEcuid = this.bike.ecuId;
										console.log("newEcuid", newEcuid)
										client.subscribe([topicalDataPoint, isCrossFence, isAuthTopic],
											async error => {
												if (!error) {
													console.log("订阅成功" + newEcuid);
												} else {
													console.log("订阅失败" + newEcuid);
												}
											});
										this.$store.commit("setCurrentBike", this.bike);
										this.$store.commit("setBlueCurrentToConnectDevice", {
											ecuId: this.bike.ecuId
										})

									} else { //如果没有连接，则重新连接订阅
										this.$store.commit("setCurrentBike", this.bike);
										this.$store.commit("setBlueCurrentToConnectDevice", {
											ecuId: this.bike.ecuId
										})
										mqttMSG();
									}

									if (this.isConnected) {
										closeBLEConnection(this.$store.state.bluetoothDevice, () => {
											bluetoothStart();
										});
									} else {
										bluetoothStart();
									}
								});

							}
						}

					}
				}
			}
		},
		methods: {
			getCarListFun() {
				this.loadingStatus = true;
				getCarListAPI().then(([err, data]) => {
					if (err) return;
					let list = data.records;
					let newList = [];
					let isHasDefaultBike = false;
					if (list.length) {
						list.forEach((element) => {
							if (this.currentBike.id == element.id) {
								element.isSelect = true;
								isHasDefaultBike = true;
							} else {
								element.isSelect = false;

							}
							newList.push({
								id: element.id,
								ecuId: element.ecuId,
								nickName: element.nickName,
								licensePlateNumber: element.licensePlateNumber,
								isAuth: element.isAuth,
								carPhotoLink: element.carPhotoLink,
								vin: element.vin,
								isSelect: element.isSelect,
								tboxExpireTime: element.tboxExpireTime
							})
						})
						//表示当前列表不含默认车辆
						if (!isHasDefaultBike) {
							if (list.length) { //如果当前用户有设备，设置第一个设备为默认车辆
								let bike = {
									id: list[0].id,
									ecuId: list[0].ecuId
								}
								this.bike = bike;
								//设为选中状态
								newList[0].isSelect = true;
							} else {
								this.bike = {};
								this.$store.commit("setCurrentBike", {});
								this.$store.commit("setDeviceData", {});
							}
						}
					} else {
						this.bike = {};
						this.$store.commit("setCurrentBike", {});
						this.$store.commit("setDeviceData", {});
					}

					this.list = newList;
					this.loadingStatus = false;
				})
			},

			toAdd: throttle(function() {
				this.$navigateTo('/pagesMy/views/addDevice');
			}),
			selectBikeFun: throttle(function(item) {
				let differenceDay = 0;
				// if(!this.$validatenull(item.tboxExpireTime)){
				// 	differenceDay = getDifferenceDay(item.tboxExpireTime);
				// }
				// if (item.isAuth == "1" && !item.isSelect) {
				// 	this.$showModal("当前车辆未认证,请先认证");
				// } else if (differenceDay < 0 && !item.isSelect) {
				// 	this.$showModal("当前车辆服务已到期,请先订阅");
				// } else {
				if (!item.isSelect) {
					console.log("车辆切换", item);
					this.list.forEach((element) => {
						element.isSelect = false;
					})
					item.isSelect = true;
					let bike = {
						id: item.id,
						ecuId: item.ecuId
					}
					this.bike = bike;

				}
				//}		
			}),
			//去认证
			gotoAuthFun: throttle(function(item) {
				this.$store.commit("setSpecialAppOnShow", true);
				if (item.isAuth == "1") {
					verifyCarAPI(item.id).then(([err, data]) => {
						if (err) return;
						let resData = JSON.parse(data);
						this.$store.commit("setVerifyUrl", resData.url)
						this.$reLaunch(`/pages/views/home/verify`)
					})
				}
			}),
			editBikeFun: throttle(function(item) {
				this.show = true;
				this.id = item.id;
				this.name = item.nickName;
			}),
			cancel() {
				this.show = false;
			},
			confirm: throttle(function() {
				this.show = false;
				editCarAPI({
					id: this.id,
					nickName: this.name
				}).then(([err, data]) => {
					if (err) return;
					//修改昵称，不用在重新刷新列表
					for (let i = 0; i < this.list.length; i++) {
						let item = this.list[i];
						if (item.id == this.id) {
							item.nickName = this.name;
							break;
						}
					}
					if (this.currentBike.id == this.id) {
						this.deviceData.nickName = this.name;
						this.$store.commit("deviceData", this.deviceData);
					}
					this.$showToast('修改车辆昵称成功');
				})
			}),

			showSelect() {
				this.selectMode = true
			},

			handleCancel() {
				this.selection = []
				this.selectMode = false
			},
			delCar(item){
				this.selection = [item.id];
				this.showDelConfirmDia();
			},

			handleDel() {
				this.hideDelConfirmDia()
				removeCarAPI(this.selection.join(",")).then(([err, data]) => {
					if (err) return;
					uni.showToast({
						title: '解绑成功'
					});
					this.getCarListFun();
				})
				this.handleCancel()
			},

		}
	}
</script>

<style>
</style>

<style lang="scss" scoped>
	::v-deep .u-checkbox {
		height: 24px;
		width: 55px;
		justify-content: center;
		position: relative;
		transform: translateX(10px);

		&>text {
			transform: scale(2);
			position: absolute;
			left: 10px;
			color: #ffffff00 !important;
			z-index: 3;
		}
	}

	::v-deep .u-loading-icon {
		margin-top: 60rpx !important;
	}

	.rz {
		::v-deep .u-icon {
			display: inline-block !important;
			margin-left: 10rpx;
		}
	}
</style>
